// index.js
const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'
const app = getApp()
import { connect } from "../index/mqtt.js";
const APIKEY = "df906d1be3d6465c8db04b3e53f49fe5";
// import { connect } from "../../utils/node_modules/mqtt/dist/mqtt" 
const SubTopic = "Leewux" //订阅数据的topic
const PubTopic = "Up-Leewux" //发布命令的topic 
Page({
    data:{
      client: null,
      Temp:0,
      Light:0,
      Soil_humi:0,
      Fan:false,
      Led:false,
      Water_pump:false,
      City:'',
    County:'',
    WeatherText :'',
    WeatherTemp : 0,
    Weathertips : '',
    Airquality : 0,
    },
  /*
    下发开关灯指令
  */
    ChangeLedStatus(event)
    {
      const that = this
      that.setData({Led:event.detail.value})
      if(event.detail.value){
         that.data.client.publish(PubTopic,"{\"Led\":1}",function(err){
            if(!err){
              console.log('成功下发指令-开灯');
            }
         })
      }else{
        that.data.client.publish(PubTopic,"{\"Led\":0}",function(err){
          if(!err){
            console.log('成功下发指令-关灯');
          }
       })
      }
    },
  /*
    下发开关风扇指令
  */
    ChangeFanStatus(event)
    {
      const that = this
      that.setData({Fan:event.detail.value})
      if(event.detail.value){
         that.data.client.publish(PubTopic,"{\"Fan\":1}",function(err){
            if(!err){
              console.log('成功下发指令-开风扇');
            }
         })
      }else{
        that.data.client.publish(PubTopic,"{\"Fan\":0}",function(err){
          if(!err){
            console.log('成功下发指令-开风扇');
          }
       })
      }
    },
  /*
    下发开关水泵指令
  */
    ChangeWaterStatus(event)
    {
      const that = this
      that.setData({Water_pump:event.detail.value})
      if(event.detail.value){
         that.data.client.publish(PubTopic,"{\"Water_pump\":1}",function(err){
            if(!err){
              console.log('成功下发指令-开水泵');
            }
         })
      }else{
        that.data.client.publish(PubTopic,"{\"Water_pump\":0}",function(err){
          if(!err){
            console.log('成功下发指令-关水泵');
          }
       })
      }
    },

    onShow(){
      const that = this
      const connectUrl = `wxs://www.leewux.top:8084/mqtt`;
      that.setData({
        client:connect(connectUrl)
      })
      that.data.client.on('connect',function(params){
        console.log("success connnect");
        wx.showToast({
          title: 'MQTT CONNECTED!',
          icon:"success",
          mask:true
        })
        that.data.client.subscribe(SubTopic,function(err){
          if(!err){
            console.log('成功订阅设备数据Topic')  
          }
        })
        that.data.client.on('message',function(topic,message){
          // console.log(topic);
          // console.log(message);
          let RecData = {}
          try {
            RecData = JSON.parse(message)
            console.log(RecData)
          } catch (error) {
            console.log('JSON解析失败')
          }
          that.setData({
            Temp:RecData.Temp,
            Light:RecData.Light,
            Soil_humi:RecData.Soil_humi,
            Fan:RecData.Fan,
            Water_pump:RecData.Water_pump,
            Led:RecData.Led
          })
          
        })
        
      })

    },
    onLoad: function (options) {
      this.getLocation()
    },
    //选择定位
  selectLocation() {
    var that = this
    wx.chooseLocation({
      success(res) {
        //console.log(res)
        that.setData({
          location: res.longitude + "," + res.latitude
        })
        that.getWeather()
        that.getCityByLoaction()
        that.getWeatherText()
        that.getAirquality()
      }
      , fail() {
        wx.getLocation({
          type: 'gcj02',
          fail() {
            wx.showModal({
              title: '获取地图位置失败',
              content: '为了给您提供准确的天气预报服务,请在设置中授权【位置信息】',
              success(mRes) {
                if (mRes.confirm) {
                  wx.openSetting({
                    success: function (data) {
                      if (data.authSetting["scope.userLocation"] === true) {
                        that.selectLocation()
                      } else {
                        wx.showToast({
                          title: '授权失败',
                          icon: 'none',
                          duration: 1000
                        })
                      }
                    }, fail(err) {
                      console.log(err)
                      wx.showToast({
                        title: '唤起设置页失败，请手动打开',
                        icon: 'none',
                        duration: 1000
                      })
                    }
                  })
                }
              }
            })
          }
        })
 
      }
    })
  },
  /**
   * 获取定位
   */
  getLocation() {
    var that = this
    wx.getLocation({
      type: 'gcj02',
      success(res) {
        that.setData({
          location: res.longitude + "," + res.latitude
        })
        that.getWeather()
        that.getCityByLoaction()
        that.getWeatherText()
        that.getAirquality()
      }, fail(err) {
        wx.showModal({
          title: '获取定位信息失败',
          content: '为了给您提供准确的天气预报服务,请在设置中授权【位置信息】',
          success(mRes) {
            if (mRes.confirm) {
              wx.openSetting({
                success: function (data) {
                  if (data.authSetting["scope.userLocation"] === true) {
                    wx.showToast({
                      title: '授权成功',
                      icon: 'success',
                      duration: 1000
                    })
                    that.getLocation()
                  } else {
                    wx.showToast({
                      title: '授权失败',
                      icon: 'none',
                      duration: 1000
                    })
                    that.setData({
                      location: "地理位置"
                    })
                    that.getWeather()
                    that.getCityByLoaction()
                  }
                }, fail(err) {
                  console.log(err)
                  wx.showToast({
                    title: '唤起设置页失败，请手动打开',
                    icon: 'none',
                    duration: 1000
                  })
                  that.setData({
                    location: "地理位置"
                  })
                  that.getWeather()
                  that.getCityByLoaction()
                }
              })
            } else if (mRes.cancel) {
              that.setData({
                location: "地理位置"
              })
              that.getWeather()
              that.getCityByLoaction()
            }
          }
        })
      }
    })
  },
  /**
   * 根据坐标获取城市信息
   */
  getCityByLoaction() {
    var that = this
    wx.request({
      url: 'https://geoapi.qweather.com/v2/city/lookup?key=' + APIKEY + "&location=" + that.data.location,
      success(result) {
        var res = result.data
        if (res.code == "200") {
          var data = res.location[0]
          that.setData({
            City: data.adm2,
            County: data.name
          })
        } else {
          wx.showToast({
            title: '获取城市信息失败',
            icon: 'none'
          })
        }
 
      }
    })
  },
  /*
    获取温度和天气具体阴晴
  */
  getWeather() {
    var that = this
    
    wx.request({
      url: 'https://devapi.qweather.com/v7/weather/now?location=' + that.data.location + "&key=" + APIKEY,
      success(result) {
        var res = result.data
        var data = res.now
        that.setData({
          WeatherText : data.text,
          WeatherTemp : data.temp
        })
      }
    })
  },
  /*
    获取舒适度指数
  */
  getWeatherText() {
    var that = this
    console.log('111')
    wx.request({
      url: 'https://devapi.qweather.com/v7/indices/1d?type=8&location=' + that.data.location + "&key=" + APIKEY,
      success(result) {
        var res = result.data
        console.log(res)
        var data = res.daily[0]
        that.setData({
          Weathertips : data.text
        })
      }
    })
  },
  /*
    获取空气质量
  */
  getAirquality() {
    var that = this
    console.log('111')
    wx.request({
      url: 'https://devapi.qweather.com/airquality/v1/now/' + that.data.location + "?key=" + APIKEY,
      success(result) {
        var res = result.data
        console.log(res)
        var data = res.aqi[0]
        that.setData({
          Airquality : data.category
        })
      }
    })
  }
})
